// pages/detail/detail.js
var WxParse = require('../../wxParse/wxParse.js');
let util = require('../../utils/util.js');
const app =getApp();
/**
* WxParse.wxParse(bindName , type, data, target,imagePadding)
* 1.bindName绑定的数据名(必填)
* 2.type可以为html或者md(必填)
* 3.data为传入的具体数据(必填)
* 4.target为Page对象,一般为this(必填)
* 5.imagePadding为当图片自适应是左右的单一padding(默认为0,可选)
*/
Page({

  /**
   * 页面的初始数据
   */
  data: {
    upImg: '../../images/spxq_sclogo.png',
    fileKey:'',
    data:{
      
    //   name:"伴手礼系列-古树滇红120g",
    //   retail_price:60,
    //   wholesale_price:48,
    //   shipping:6,
    //   tags:["正品保障","极速发货"],
    //   video:"",
    //   desc:["茶，(学名:Camellia sinensis (L.) O. Ktze.)，灌木或小乔木，嫩枝无毛。叶革质，长圆形或椭圆形，先端钝或尖锐，基部楔形，上面发亮，下面无毛或初时有柔毛，边缘有锯齿，叶柄无毛。",
    // "花白色，花柄有时稍长;萼片阔卵形至圆形，无毛，宿存;花瓣阔卵形，基部略连合，背面无毛，有时有短柔毛;子房密生白毛;花柱无毛。蒴果3球形或1-2球形，高1.1-1.5厘米，每球有种子1-2粒。花期10月至翌年2月。"],
    //   pics:["",""]
    },
    showPopOutStatus:0,//{0:hidden,1:addCart,2:buy}
    activeBtn:0,//弹出层选择的规格选项编号
    currentNum:1,//弹出层stepper数量
    checkBoxStatus:false,
    fileKey:'',//logofileKey
    decommand:'',//定制要求
    user:{

    },
  },
  changeSpecif:function(event){
    // console.log(event.currentTarget.dataset.id);
    let data = this.data,
      checkBoxStatus = data.checkBoxStatus,
      num = event.currentTarget.dataset.id;
    if ((num == 0 && data.currentNum < 2 * data.data.specification) || (num == 1 && data.currentNum < 2)){
      console.log('未达成定制条件')
      checkBoxStatus = false
    }
    this.setData({
      activeBtn: num,
      checkBoxStatus
    })
  },
  changeCount:function(event) {
    let newCount = this.data.currentNum*1+event.currentTarget.dataset.id*1;
    let checkBox = this.data.checkBoxStatus;

    if (newCount<2 ) {
      checkBox = false;
    }
    if(newCount<1) newCount=1;
    this.setData({
      // currentNum:this.data.currentNum*1+event.currentTarget.dataset.id*1
      currentNum:newCount,
      checkBoxStatus:checkBox
    })
  },
  checkBoxFn:function(event) {
    if (this.data.checkBoxStatus){
      this.setData({checkBoxStatus:false})
    }
    
    else if(this.data.activeBtn==0){
      if (this.data.currentNum >= (2 * this.data.data.specification)){
        this.setData({
          checkBoxStatus: true
        })
        return;
      }
      else{
        wx.showToast({
          title: `选择${(2 * this.data.data.specification)}套袋以上货物才能定制logo哦~`,
          icon: "none",
          duration: 1500
        })
        return;
      }
    }
    else if (this.data.currentNum < 2) {
      wx.showToast({
        title: "选择2件以上货物才能定制logo哦~",
        icon: "none",
        duration: 1500
      })
      return;
    }
    else if (this.data.currentNum>=2) {
      this.setData({
        checkBoxStatus:true
      })
    }
    // }else{
    //   wx.showToast({
    //     title:"请选择按件购买",
    //     icon:"none",
    //     duration:1500
    //   })
  },
  showPopOut:function(e){
    this.setData({
      showPopOutStatus:e.currentTarget.dataset.i ////{0:hidden,1:addCart,2:buy}
    })
  },
  goTab(e){
    wx.switchTab({
      url:"../"+e.currentTarget.dataset.tab+"/"+e.currentTarget.dataset.tab
    })
  },
  handleSubmit:function(e){
    this.setData({
      ta_focus:'false',
      concent: this.data.decommand
    })
    console.log("get value"+this.data.decommand)
    console.log("showStatus",this.showPopOutStatus)
    if(this.data.showPopOutStatus == 1 )
      this.addToCart();
    else 
      this.toPay()
  },
  addToCart(succ=()=>{}){
    let that = this
    wx.showToast({
      title:"正在加入购物车",
      icon:"loading"
    })
    let count = this.data.currentNum,
      dzLogo = this.data.checkBoxStatus,
      productId  = this.data.data.id,
      dzDecommand = this.data.decommand,
      fileKey = this.data.fileKey,
      name = this.data.data.productName,
      pictureUrl = encodeURIComponent(this.data.data.slideShowUrl[1]),
      primeCost = this.data.data.primeCost,
      cost = primeCost * count,
      postage = this.data.data.postage
    let product = {
      isCustomization: dzLogo,
      logoDemand: dzDecommand,
      logoFileKey: fileKey,
      productId: productId,
      primeCost: primeCost,
    }
    that.data.activeBtn==0?product['bagNum']=count:product['pieceNum']=count
    util.post({
      url:'https://groomtea.icebartech.com/api/miniApp/shoppingTrolley/saveShoppingTrolley',
      data:product,
      success:res=>{
        console.log(res);
        product.id = res.data.bussData;
        product.name=name;
        product.pictureUrl=pictureUrl;
        product.cost=cost;
        product.postage = postage;
        let proStr = JSON.stringify(product)
        console.log(proStr)
        if (that.data.showPopOutStatus==1)
          wx.showToast({
            title:"添加成功",
            icon:"success",
            duration:800
          })
        that.setData({proStr:proStr,showPopOutStatus:0})
      },
      fail:res=>{
        console.log(res);
      }
    })
  },
  toPay(){
    console.log("topay")
    let data = this.data
    let count = data.currentNum,
      dzLogo = data.checkBoxStatus,
      productId = data.data.id,
      dzDecommand = data.decommand,
      fileKey = data.fileKey,
      name = data.data.productName,
      pictureUrl = encodeURIComponent(this.data.data.slideShowUrl[1]),
      primeCost = data.data.primeCost,
      specification = data.data.specification,
      postage = data.data.postage,
      cost = data.activeBtn == 0 ? primeCost * count : primeCost * count * specification;
    console.log(dzDecommand)
    let product = {
      isCustomization: dzLogo,
      logoDemand: dzDecommand,
      logoFileKey: fileKey,
      productId: productId,
      primeCost: primeCost,
    }
    data.activeBtn == 0 ? product['bagNum'] = count : product['pieceNum'] = count
    util.post({
      url: 'https://groomtea.icebartech.com/api/miniApp/shoppingTrolley/saveShoppingTrolley',
      data: product,
      success: res => {
        console.log(res);
        product.id = res.data.bussData;
        product.name = name;
        product.pictureUrl = pictureUrl;
        product.cost = cost;
        product.specification = specification
        product.postage = postage;
        let proStr = JSON.stringify(product)
        console.log(proStr)
        wx.navigateTo({
          url: `../balance/balance?carts=${proStr}`
        })
      },
      fail:res=>{
        console.log(res);
      }
    })
    
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    let productid = parseInt(options.id);//parseInt(options.id);
    console.log('options',options);
    util.post({
      url: 'https://groomtea.icebartech.com/api/miniApp/product/productDetail',
      header: { 'content-type': 'application/x-www-form-urlencoded' },
      data:{
        id: productid
      },
      success:(res)=> {
        console.log('res-----',res)
        var article = res.data.bussData.productDetail;
        WxParse.wxParse('article', 'html', article, that,5);
        let user = app.globalData.userInfo;
        this.setData({
          data:res.data.bussData,
          user:user
        })
      },
      fail:res=>{
        console.log(res);
      }
    });
    

  },
//上传logo
  upImg(){
    let that = this;
    wx.chooseImage({
      count: 1,
      success: function (res) {
        let tempFilePaths = res.tempFilePaths[0],
            tempFile = res.tempFiles[0];
        console.log('chooseImage-------',res);
        if(tempFile.size/1024/1024>2){
        wx.showToast({
          title:'大小不能超过2M'
        })
        return false;
      };
      that.upload(tempFilePaths,tempFile)
    }, 
          fail:(res)=>{
            console.log(res);
          }
        });
  },
  upload(path,file){
    let that = this;
    console.log('上传图片');
    let suffix = /\.[^\.]+$/.exec(path)[0].slice(1);
    let contentType = '';
    if(suffix == 'jpg' || suffix == 'jpeg'){
      contentType = 'image/' + 'jpeg'
    }else{
      contentType = 'image/' + suffix
    }
    console.log('去获取链接',suffix,contentType);
    let url = 'https://groomtea.icebartech.com/api/base/sys/mini/getOSSUploadFormData';
    let dataForm = {
      suffix:suffix,
      contentType:contentType
    }
    util.http({
      url: url,
      dataForm:dataForm,
      success: function (res) {
        console.log('获得上传链接',res.data.bussData.formData,path);
        let resData = res.data.bussData;
        let formData = Object.assign(resData.formData,{name:path})
        let uploadUrl = resData.uploadUrl;
        let fileKey = resData.fileKey;
        that.data.fileKey = fileKey
        console.log('formData----',formData);
        wx.uploadFile({
          url:uploadUrl,
          filePath:path,
          name:'file',
          formData:formData,
          success(res){
            const data = res.data;
            console.log('success--',res);
            util.post({
              url:'https://groomtea.icebartech.com/api/admin/base/getGenerateDownloadUrl',
              header: { 'content-type': 'application/x-www-form-urlencoded' },
              data:{
                fileKey:fileKey,
              },
              success:res=>{
                console.log(res);
                let img = res.data.bussData;
                that.setData({
                  upImg:img,
                  fileKey:fileKey
                })
              },
              fail:err=>{
                console.log(err);
              }
            })
          },
          fail:function(e){
            console.log('上传失败')
          }
        })
        if(res.data.status == 401){
          wx.showToast({
            title: '登录已过期,请重新登陆',
            icon: 'none'
          })
          wx.clearStorageSync();
          wx.navigateTo({
            url: '../login/login',
          })
          return;
        }
      },
      fail: err => {
        console.log(err);
        wx.hideToast();
        wx.showModal({
          title: '错误提示',
          content: '上传图片失败',
          showCancel: false,
          success: function (res) { }
        })
        fail && fail(err)
      }
    })
  },

  getDemmand(e){
    console.log(e);
    this.data.decommand=e.detail.value
  },

  remindYwy(){
    wx.showToast({
      title: '业务员暂未开放零售功能',
      icon:'none'
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})